package com.aptemo.webetek.client;

import java.util.Iterator;

import com.aptemo.webetek.client.commands.GotAsynchCallback;
import com.aptemo.webetek.client.commands.impl.GetCurrentUserDetailsAction;
import com.aptemo.webetek.client.commands.impl.GetLoginInfoAction;
import com.aptemo.webetek.client.commands.impl.GetStatisticsAction;
import com.aptemo.webetek.client.commands.impl.GetStatisticsAction.EStatsPeriod;
import com.aptemo.webetek.client.commands.impl.GetStatisticsAction.EStatsTarget;
import com.aptemo.webetek.client.events.AddBetEvent;
import com.aptemo.webetek.client.events.AddTeamEvent;
import com.aptemo.webetek.client.events.AddTeamHandler;
import com.aptemo.webetek.client.events.BetPlacedEvent;
import com.aptemo.webetek.client.events.BetSelectionEventHandler;
import com.aptemo.webetek.client.events.GameListUpdatedEvent;
import com.aptemo.webetek.client.events.GameListUpdatedHandler;
import com.aptemo.webetek.client.events.PickSelectedEvent;
import com.aptemo.webetek.client.events.PickSelectedHandler;
import com.aptemo.webetek.client.events.PlayerHandler;
import com.aptemo.webetek.client.events.PlayerListUpdatedEvent;
import com.aptemo.webetek.client.events.RefreshEventHandler;
import com.aptemo.webetek.client.events.ResultAssignedEvent;
import com.aptemo.webetek.client.events.SelectedBetEvent;
import com.aptemo.webetek.client.events.SelectedPlayerEvent;
import com.aptemo.webetek.client.events.SelectedPlayerHandler;
import com.aptemo.webetek.client.events.StakeSelectedEvent;
import com.aptemo.webetek.client.events.StakeSelectedHandler;
import com.aptemo.webetek.client.events.TeamAddedEvent;
import com.aptemo.webetek.client.events.TeamChangedEvent;
import com.aptemo.webetek.client.events.TeamChangedHandler;
import com.aptemo.webetek.client.events.TeamDeletedEvent;
import com.aptemo.webetek.client.events.TeamUpdatedEvent;
import com.aptemo.webetek.client.events.TeamUpdatedHandler;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.client.mvp.BasePresenter;
import com.aptemo.webetek.client.utils.TokenUtils;
import com.aptemo.webetek.client.widgets.CenterWidget;
import com.aptemo.webetek.client.widgets.HeaderWidget;
import com.aptemo.webetek.client.widgets.LoginProposalWidget;
import com.aptemo.webetek.client.widgets.betslip.BetSlip;
import com.aptemo.webetek.client.widgets.betslip.BetSlipPresenter;
import com.aptemo.webetek.client.widgets.games.GameResume;
import com.aptemo.webetek.client.widgets.games.GameResumePresenter;
import com.aptemo.webetek.client.widgets.games.Games;
import com.aptemo.webetek.client.widgets.games.GamesPagingPresenter;
import com.aptemo.webetek.client.widgets.payments.Payments;
import com.aptemo.webetek.client.widgets.payments.PaymentsPagingPresenter;
import com.aptemo.webetek.client.widgets.players.PlayerResume;
import com.aptemo.webetek.client.widgets.players.PlayerResumePresenter;
import com.aptemo.webetek.client.widgets.players.Players;
import com.aptemo.webetek.client.widgets.players.PlayersPagingPresenter;
import com.aptemo.webetek.client.widgets.scoreboard.TeamStandings;
import com.aptemo.webetek.client.widgets.scoreboard.TeamStandingsPagingPresenter;
import com.aptemo.webetek.client.widgets.stakes.Stakes;
import com.aptemo.webetek.client.widgets.stakes.StakesPagingPresenter;
import com.aptemo.webetek.client.widgets.statistics.ApplicationStatistics;
import com.aptemo.webetek.client.widgets.statistics.UserStatistics;
import com.aptemo.webetek.client.widgets.teams.TeamHeader;
import com.aptemo.webetek.client.widgets.teams.TeamHeaderPresenter;
import com.aptemo.webetek.client.widgets.teams.UserGroupResume;
import com.aptemo.webetek.client.widgets.teams.UserGroupResumePresenter;
import com.aptemo.webetek.client.widgets.teams.UserGroups;
import com.aptemo.webetek.client.widgets.teams.UserGroupsPresenter;
import com.aptemo.webetek.client.widgets.userinfo.UserInfo;
import com.aptemo.webetek.client.widgets.userinfo.UserInfoPresenter;
import com.aptemo.webetek.client.widgets.window.WindowContainer;
import com.aptemo.webetek.shared.LoginBean;
import com.aptemo.webetek.shared.StatisticsBean;
import com.aptemo.webetek.shared.UserBean;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class WebetekLayoutPresenter implements BasePresenter, ValueChangeHandler<String>
{
	public interface Display
	{
		HasWidgets getWestTopPanel();

		HasWidgets getWestMiddlePanel();

		HasWidgets getCenterTopPanel();

		HasWidgets getCenterMiddlePanel();

		HasWidgets getEastTopPanel();

		HasWidgets getEastMiddlePanel();

		HasWidgets getEastBottomPanel();

		HasWidgets getTopPanel();

	}

	private WebetekUserServiceAsync			rpcService;
	private HandlerManager					eventBus;
	private Display							layout;
	private BetSlipPresenter				betSlipPresenter;
	private LoginBean						loginInfo;
	private UserBean						currentUser;
	private String							currentTeamId;

	private GamesPagingPresenter			games;
	private PlayersPagingPresenter			players;
	private PaymentsPagingPresenter			payments;
	private TeamStandingsPagingPresenter	standings;

	private StakesPagingPresenter			stakes;

	public WebetekLayoutPresenter(Display view, WebetekUserServiceAsync rpcService, HandlerManager eventBus)
	{
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.layout = view;
	}

	private void checkLogin()
	{
		String path = Window.Location.getPath() + Window.Location.getQueryString() + Window.Location.getHash();

		GetLoginInfoAction action = new GetLoginInfoAction(path);
		rpcService.invoke(action, new AsyncCallback<LoginBean>()
		{

			@Override
			public void onFailure(Throwable caught)
			{
				// 
				DialogBox box = new DialogBox(true);
				box.setText("Error getting user from server!");
				box.show();
			}

			@Override
			public void onSuccess(LoginBean result)
			{
				// save user object
				WebetekLayoutPresenter.this.loginInfo = result;

				// continue application
				enter();

			}
		});
	}

	@Override
	public void go(HasWidgets main)
	{
		// check login info and enter
		checkLogin();

		// init containers
		// main.clear();
		// main.add(layout.getDisplay());

		bind();
	}

	private void enter()
	{
		// get topbar container
		HasWidgets topBar = RootPanel.get("topNavPanel");
		topBar.clear();
		// init user info widget
		UserInfo userInfoWidget = new UserInfo();
		UserInfoPresenter userInfoPresenter = new UserInfoPresenter(loginInfo, eventBus, rpcService, userInfoWidget);
		userInfoPresenter.go(topBar);
		topBar.add(userInfoWidget);

		// default widgets...

		// teams...
		doUpdateTeams();
		doShowStatistics();

		// check history
		if ("".equals(History.getToken()))
		{
			// intro...
			History.newItem("home");
		}
		else
		{
			History.fireCurrentHistoryState();
		}
	}

	private void bind()
	{
		History.addValueChangeHandler(this);

		eventBus.addHandler(AddTeamEvent.TYPE, new AddTeamHandler()
		{
			@Override
			public void onTeamAdd(String id)
			{
				// History.newItem("addTeam");
				doEditTeam(null);
			}
		});

		eventBus.addHandler(TeamChangedEvent.TYPE, new TeamChangedHandler()
		{

			@Override
			public void onTeamChanged(TeamChangedEvent event)
			{
				String id = event.getId();

				// doChangeTeam(id, "", 0);
				// doGameListUpdated(id, "", "", 0);

				History.newItem("group-" + id);
			}
		});

		eventBus.addHandler(SelectedBetEvent.TYPE, new BetSelectionEventHandler()
		{

			@Override
			public void onSelection(SelectedBetEvent event)
			{
				String id = event.getId();
				String teamid = event.getTeamId();
				doShowBet(id, teamid);

				// History.newItem("bet-" + id, false);
			}
		});

		eventBus.addHandler(BetPlacedEvent.TYPE, new RefreshEventHandler()
		{

			@Override
			public void onRefresh(String teamId)
			{
				int pageNo = extractPagingInfo(History.getToken());
				// 
				doShowEvents(teamId, "", "", pageNo);
				// 
				doShowStakes(teamId, "", 0, layout.getEastMiddlePanel());

				// updateTeamInfo(teamId, true);
				updateUserInfo("", teamId);
			}
		});

		eventBus.addHandler(TeamAddedEvent.TYPE, new TeamUpdatedHandler()
		{

			@Override
			public void onTeamUpdated(String id)
			{
				doUpdateTeams();

				if ((id != null) && (!id.isEmpty()))
				{
					History.newItem("group-" + id);
				}
			}
		});

		eventBus.addHandler(TeamDeletedEvent.TYPE, new TeamUpdatedHandler()
		{

			@Override
			public void onTeamUpdated(String id)
			{
				History.newItem("home");
				doUpdateTeams();
			}
		});

		eventBus.addHandler(TeamUpdatedEvent.TYPE, new TeamUpdatedHandler()
		{

			@Override
			public void onTeamUpdated(String teamId)
			{
				doUpdateTeams();
				updateTeamInfo(teamId, true);
			}
		});

		eventBus.addHandler(AddBetEvent.TYPE, new AddTeamHandler()
		{
			@Override
			public void onTeamAdd(String teamid)
			{
				doAddBet(teamid);
			}
		});

		eventBus.addHandler(GameListUpdatedEvent.TYPE, new GameListUpdatedHandler()
		{

			@Override
			public void onGameListUpdated(GameListUpdatedEvent event)
			{
				int pageNo = extractPagingInfo(History.getToken());

				// TODO event.getFilter()
				String status = TokenUtils.getTokenValue(History.getToken(), "filter");

				doShowEvents(event.getTeamId(), "", status, pageNo);
			}
		});

		eventBus.addHandler(SelectedPlayerEvent.TYPE, new SelectedPlayerHandler()
		{
			@Override
			public void onSelection(SelectedPlayerEvent event)
			{
				doUpdatePlayers(event.getId(), event.getTeamId());
			}
		});

		eventBus.addHandler(PlayerListUpdatedEvent.TYPE, new PlayerHandler()
		{
			@Override
			public void onPlayerAction(String id)
			{
				int pageNo = extractPagingInfo(History.getToken());

				doShowMembers(id, "", pageNo);
			}
		});

		eventBus.addHandler(StakeSelectedEvent.TYPE, new StakeSelectedHandler()
		{
			@Override
			public void onStakeSelected(StakeSelectedEvent event)
			{
				doShowBetSlip(event.getId(), event.getTeamId());
			}

		});

		eventBus.addHandler(PickSelectedEvent.TYPE, new PickSelectedHandler()
		{
			@Override
			public void onPicked(PickSelectedEvent event)
			{
				if (betSlipPresenter != null)
				{
					betSlipPresenter.addSelectedPick(event.getPick());
				}
			}
		});

		eventBus.addHandler(ResultAssignedEvent.TYPE, new RefreshEventHandler()
		{

			@Override
			public void onRefresh(String teamId)
			{
				doShowEvents(teamId, "", "", 0);
				doShowStakes(teamId, "", 0, layout.getEastMiddlePanel());
				updateUserInfo("", teamId);
			}
		});

	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event)
	{
		String token = event.getValue();
		String teamId = extractTeam(token);

		if (teamId != null && hasTeamChanged(teamId))
		{
			updateUserInfo(token, teamId);
		}
		else
		{
			dispatchHistoryEvent(token, teamId);

		}
	}

	private void updateUserInfo(final String token, final String teamId)
	{
		// get user...
		GetCurrentUserDetailsAction action = new GetCurrentUserDetailsAction(teamId);
		rpcService.invoke(action, new GotAsynchCallback<UserBean>()
		{
			@Override
			public void onError(String message, EErrorCodes code)
			{
				currentUser = null;
				currentTeamId = teamId;
				updateTeamInfo(teamId, true);

				layout.getCenterTopPanel().clear();

				doShowBetSlip(null, teamId, true);
				doShowStakes(teamId, "", 0, layout.getEastMiddlePanel());
				updateUserStats(teamId);

				// dispatch
				dispatchHistoryEvent(token, teamId);
			}

			@Override
			public void onSuccess(UserBean user)
			{
				currentTeamId = teamId;
				currentUser = user;
				// update team info...
				updateTeamInfo(teamId, true);

				layout.getCenterTopPanel().clear();

				// show bet slip entry text...
				doShowBetSlip(null, teamId, true);
				// update user and team stats...
				updateUserStats(teamId);
				// update stakes...
				doShowStakes(teamId, "", 0, layout.getEastMiddlePanel());

				// dispatch
				dispatchHistoryEvent(token, teamId);
			}
		});

	}

	private void dispatchHistoryEvent(String token, final String teamId)
	{
		int pageNo = extractPagingInfo(token);
		String filter = extractTokenValue(token, "filter");

		//
		if (token.equals("home"))
		{
			doHome();
		}
		else if (token.contains("group-"))
		{
			// String teamId = extractTeam(token, "group");
			String tagId = extractTokenValue(token, "label");

			// doChangeTeam(teamId, tagId, pageNo);
			doShowEvents(teamId, tagId, filter, pageNo);
		}
		else if (token.contains("groupedit-"))
		{
			// String teamId = extractTeam(token, "groupedit");
			doEditTeam(teamId);
		}
		else if (token.equals("addTeam"))
		{
			doEditTeam(teamId);
		}
		else if (token.contains("members-"))
		{
			// String id = token.split("-")[1];
			doShowMembers(teamId, "", pageNo);
		}

		else if (token.contains("stake"))
		{
			// String id = extractTeam(token, "stake");
			doShowStakes(teamId, filter, pageNo);
		}
		else if (token.contains("payments"))
		{
			// String id = extractTeam(token, "payments");
			doShowPayments(teamId, filter, pageNo);
		}
		else if (token.contains("groups"))
		{
			// int pageNo = extractPagingInfo(token);
			doShowTeams(pageNo);
		}
		else if (token.contains("standings"))
		{
			// String id = extractTeam(token, "standings");
			// int pageNo = extractPagingInfo(token);
			doShowTeamStandings(teamId, pageNo);
		}
	}

	private String extractTokenValue(String token, String tokenName)
	{
		String tokens[] = token.split("/");

		for (int i = 0; i < tokens.length; i++)
		{
			if (tokens[i].contains(tokenName))
			{
				String pair[] = tokens[i].split("-");

				if (pair.length < 2)
				{
					return null;
				}

				return pair[1];
			}
		}
		return null;
	}

	protected String extractTeam(String token)
	{
		String tokens[] = token.split("-");

		if (tokens.length > 0)
		{
			if (tokens.length >= 2)
			{
				// extract paging data
				String paging[] = tokens[1].split("/");
				String teamId = paging[0];
				return teamId;
			}

		}
		return "";
	}

	protected String extractTeam(String token, String ident)
	{
		String tokens[] = token.split("-");

		if (tokens.length > 0)
		{
			if (tokens[0].equals(ident) && (tokens.length >= 2))
			{
				// extract paging data
				String paging[] = tokens[1].split("/");
				String teamId = paging[0];
				return teamId;
			}

		}
		return "";
	}

	protected String extractBetGroup(String token)
	{
		String tokens[] = token.split("-");

		if (tokens.length > 0)
		{
			if (tokens[0].equals("group") && (tokens.length >= 3))
			{
				// extract paging data
				String paging[] = tokens[2].split("/");
				String teamId = paging[0];
				return teamId;
			}

		}
		return "";
	}

	private boolean hasTeamChanged(String teamId)
	{
		if (teamId == null || teamId.isEmpty())
		{
			return false;
		}

		if (currentTeamId != null && !teamId.equals(currentTeamId))
		{
			return true;
		}
		if (currentTeamId == null && teamId != null && !teamId.isEmpty())
		{
			return true;
		}
		return false;
	}

	private int extractPagingInfo(String token)
	{
		int pageNo = 0;

		String pageIdStr = TokenUtils.getTokenValue(token, "page");
		try
		{
			pageNo = Integer.parseInt(pageIdStr);
		}
		catch (NumberFormatException e)
		{
			pageNo = 0;
		}
		return pageNo;
	}

	private void doHome()
	{
		// do some cleaning...
		this.currentTeamId = "";
		// TODO info about teams...
		// DO the top panel...
		HasWidgets top = layout.getTopPanel();
		top.clear();
		top.add(new HeaderWidget(loginInfo));

		HasWidgets topcenter = layout.getCenterTopPanel();
		topcenter.clear();
		topcenter.add(new CenterWidget());

		layout.getCenterMiddlePanel().clear();
		layout.getEastTopPanel().clear();
		layout.getEastMiddlePanel().clear();
		layout.getEastMiddlePanel().add(new VerticalAd());
		layout.getEastBottomPanel().clear();
	}

	private void doEditTeam(String teamId)
	{

		if (!loginInfo.isLoggedIn())
		{
			// report login
			// render top center panel
			HasWidgets panel = layout.getCenterTopPanel();
			panel.add(new LoginProposalWidget());
			return;
		}
		// render top center panel
		HasWidgets panel = layout.getCenterTopPanel();
		UserGroupResume decoree = new UserGroupResume();

		WindowContainer wnd = new WindowContainer(decoree);
		wnd.go(panel);

		UserGroupResumePresenter resumePresenter = new UserGroupResumePresenter(currentUser, decoree, eventBus, rpcService, teamId, loginInfo.getEmail());
		resumePresenter.go(wnd.getDecoreePanel());
	}

	private void doShowMembers(String teamId, String filter, int pageNo)
	{
		HasWidgets contentPanel = layout.getCenterMiddlePanel();
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		if (players == null || (cw == null) || (cw != null && !(cw instanceof Players)))
		{
			Players decoree = new Players();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			players = new PlayersPagingPresenter(currentUser, decoree, eventBus, rpcService, teamId, filter, pageNo);
			players.go(wnd.getDecoreePanel());
		}
		else
		{
			players.update(currentUser, teamId, filter, pageNo);
		}
	}

	private void doAddBet(String teamid)
	{
		HasWidgets top = layout.getCenterTopPanel();
		top.clear();

		GameResume gr = new GameResume();
		WindowContainer wnd = new WindowContainer(gr);
		wnd.go(top);

		GameResumePresenter pres = new GameResumePresenter(currentUser, gr, eventBus, rpcService, null, teamid);
		pres.go(wnd.getDecoreePanel());
	}

	private void doShowBet(String betid, String teamid)
	{
		if ((betid != null) && (!betid.isEmpty()))
		{
			HasWidgets top = layout.getCenterTopPanel();
			top.clear();

			GameResume gr = new GameResume();
			WindowContainer wnd = new WindowContainer(gr);
			wnd.go(top);

			GameResumePresenter pres = new GameResumePresenter(currentUser, gr, eventBus, rpcService, betid, teamid);
			pres.go(wnd.getDecoreePanel());
		}

		if (hasTeamChanged(teamid))
		{
			doShowEvents(teamid, "", "", 0);
		}

	}

	private void doShowEvents(String teamid, String tagId, String filter, int pageNo)
	{
		HasWidgets contentPanel = layout.getCenterMiddlePanel();
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		if (games == null || (cw == null) || (cw != null && !(cw instanceof Games)))
		{
			Games decoree = new Games();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			games = new GamesPagingPresenter(currentUser, decoree, eventBus, rpcService, teamid, tagId, filter, pageNo);
			games.go(wnd.getDecoreePanel());
		}
		else
		{
			games.update(currentUser, teamid, tagId, filter, pageNo);
		}

	}

	private Widget getContainedWidget(HasWidgets container)
	{
		Iterator<Widget> it = container.iterator();
		if (it.hasNext())
		{
			Widget w = it.next();

			if (w instanceof WindowContainer)
			{
				WindowContainer wc = (WindowContainer) w;
				Widget wid = wc.getWidget();

				return wid;
			}
			else
			{
				return w;
			}
		}
		return null;

	}

	private void doUpdateTeams()
	{
		//
		UserGroups teams = new UserGroups();
		UserGroupsPresenter teamsPresenter = new UserGroupsPresenter(loginInfo.isAdmin(), teams, eventBus, rpcService);
		teamsPresenter.go(layout.getWestMiddlePanel());
	}

	protected void doUpdatePlayers(String id, String teamId)
	{
		// 
		HasWidgets container = layout.getCenterTopPanel();

		PlayerResume decoree = new PlayerResume();

		WindowContainer wnd = new WindowContainer(decoree);
		wnd.go(container);

		PlayerResumePresenter pres = new PlayerResumePresenter(decoree, eventBus, rpcService, id, teamId);
		pres.go(wnd.getDecoreePanel());
	}

	private void doShowStakes(String teamId, String filter, int pageNo)
	{
		// doShowStakes(teamId, filter, pageNo, layout.getCenterMiddlePanel());

		boolean reload = false;
		HasWidgets contentPanel = layout.getCenterMiddlePanel();
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		if (reload || stakes == null || (cw == null) || (cw != null && !(cw instanceof Stakes)))
		{
			Stakes decoree = new Stakes();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			stakes = new StakesPagingPresenter(decoree, eventBus, rpcService, teamId, filter, pageNo);
			stakes.go(wnd.getDecoreePanel());
		}
		else
		{
			stakes.update(currentUser, teamId, filter, pageNo);
		}

	}

	private void doShowStakes(String teamId, String filter, int pageNo, HasWidgets contentPanel)
	{
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		// if (reload || stakes == null || (cw == null) || (cw != null && !(cw
		// instanceof Stakes)))
		{
			Stakes decoree = new Stakes();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			StakesPagingPresenter stakes = new StakesPagingPresenter(decoree, eventBus, rpcService, teamId, filter, pageNo);
			stakes.go(wnd.getDecoreePanel());
		}
		// else
		// {
		// stakes.update(currentUser, teamId, filter, pageNo);
		// }

	}

	private void doShowPayments(String teamId, String filter, int pageNo)
	{
		HasWidgets contentPanel = layout.getCenterMiddlePanel();
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		if (payments == null || (cw == null) || (cw != null && !(cw instanceof Payments)))
		{
			Payments decoree = new Payments();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			// PaymentsPresenter payPresenter = new PaymentsPresenter(payments,
			// eventBus, rpcService, teamId, pageNo);
			payments = new PaymentsPagingPresenter(currentUser, decoree, eventBus, rpcService, teamId, filter, pageNo);
			payments.go(wnd.getDecoreePanel());
		}
		else
		{
			payments.update(currentUser, teamId, filter, pageNo);
		}

	}

	private void doShowTeams(int pageNo)
	{
		HasWidgets contentPanel = layout.getCenterMiddlePanel();

		UserGroups teams = new UserGroups();
		UserGroupsPresenter presenter = new UserGroupsPresenter(loginInfo.isAdmin(), teams, eventBus, rpcService, true, 0);
		presenter.go(contentPanel);
	}

	private void doShowBetSlip(String id, String teamId)
	{
		doShowBetSlip(id, teamId, false);
	}

	private void doShowBetSlip(String id, String teamId, boolean forceReload)
	{
		// remeber betslip
		if (betSlipPresenter == null || forceReload)
		{
			BetSlip decoree = new BetSlip();
			HasWidgets panel = layout.getEastTopPanel();

			panel.clear();
			// WindowContainer wnd = new WindowContainer(decoree);
			// wnd.go(panel);

			betSlipPresenter = new BetSlipPresenter(decoree, eventBus, rpcService, id, teamId);
			betSlipPresenter.go(panel);
		}
		else
		{
			betSlipPresenter.addSelectedStake(id);
		}
	}

	private void doShowTeamStandings(String teamId, int pageNo)
	{

		HasWidgets contentPanel = layout.getCenterMiddlePanel();
		Widget cw = getContainedWidget(contentPanel);

		// lazy instantiation...
		if (standings == null || (cw == null) || (cw != null && !(cw instanceof TeamStandings)))
		{
			TeamStandings decoree = new TeamStandings();
			WindowContainer wnd = new WindowContainer(decoree);
			wnd.go(contentPanel);

			// PaymentsPresenter payPresenter = new PaymentsPresenter(payments,
			// eventBus, rpcService, teamId, pageNo);
			standings = new TeamStandingsPagingPresenter(decoree, eventBus, rpcService, teamId, pageNo);
			standings.go(wnd.getDecoreePanel());
		}
		else
		{
			standings.update(currentUser, teamId, "", pageNo);
		}

		// updateTeamInfo(teamid);
		// TeamStandings decoree = new TeamStandings();
		//
		// HasWidgets contentPanel = layout.getCenterMiddlePanel();
		// WindowContainer wnd = new WindowContainer(decoree);
		// wnd.go(contentPanel);
		//
		// TeamStandingsPagingPresenter presenter = new
		// TeamStandingsPagingPresenter(decoree, eventBus, rpcService, teamid,
		// pageNo);
		// presenter.go(wnd.getDecoreePanel());

	}

	private void updateUserStats(String teamid)
	{
		HasWidgets contentPanel = layout.getEastBottomPanel();
		contentPanel.clear();
		// contentPanel.add(statsDisplay);

		if (currentUser == null)
		{
			return;
		}

		UserStatistics decoree = new UserStatistics(currentUser, loginInfo);

		WindowContainer wnd = new WindowContainer(decoree);
		wnd.go(contentPanel);

		// GetStatisticsAction uaction = new
		// GetStatisticsAction(EStatsTarget.EUSER, EStatsPeriod.EMONTH, teamid);
		// rpcService.invoke(uaction, new GotAsynchCallback<StatisticsBean>()
		// {
		//
		// @Override
		// public void onSuccess(StatisticsBean stats)
		// {
		// UserStatistics statsDisplay = new UserStatistics(stats, loginInfo);
		// layout.getEastBottomPanel().clear();
		// layout.getEastBottomPanel().add(statsDisplay);
		// }
		//
		// @Override
		// public void onError(String message, EErrorCodes code)
		// {
		// // TODO Auto-generated method stub
		//
		// }
		// });

	}

	// private void doEditTeam(String id)
	// {
	// // updateTeamInfo(id);
	//
	// // render top center panel
	// HasWidgets center = layout.getCenterTopPanel();
	//
	// UserGroupResume decoree = new UserGroupResume();
	// WindowContainer wnd = new WindowContainer(decoree);
	// wnd.go(center);
	//
	// UserGroupResumePresenter resumePresenter = new
	// UserGroupResumePresenter(currentUser, decoree, eventBus, rpcService, id);
	// resumePresenter.go(wnd.getDecoreePanel());
	//
	// }

	private void doShowStatistics()
	{
		// load statistics...
		GetStatisticsAction action = new GetStatisticsAction(EStatsTarget.EALL, EStatsPeriod.EMONTH);
		rpcService.invoke(action, new GotAsynchCallback<StatisticsBean>()
		{

			@Override
			public void onSuccess(StatisticsBean stats)
			{
				HasWidgets panel = layout.getWestTopPanel();
				panel.clear();

				ApplicationStatistics decoree = new ApplicationStatistics(stats);
				WindowContainer wnd = new WindowContainer(decoree);
				wnd.go(panel);

				panel.add(decoree);
			}

			@Override
			public void onError(String message, EErrorCodes code)
			{
				// TODO Auto-generated method stub

			}
		});
	}

	private void updateTeamInfo(String teamId)
	{
		updateTeamInfo(teamId, false);
	}

	private void updateTeamInfo(String teamId, boolean forceReload)
	{
		// check if top panel empty
		HasWidgets top = layout.getTopPanel();
		Iterator<Widget> it = top.iterator();
		if (!it.hasNext() || forceReload)
		{
			if (teamId != null && !teamId.isEmpty())
			{
				TeamHeader th = new TeamHeader();
				TeamHeaderPresenter thp = new TeamHeaderPresenter(teamId, th, eventBus, rpcService, currentUser);
				thp.go(top);
			}
			else
			{
				// TODO commercials...
			}
		}

	}

}
